package com.fang.gateway.security.handler;

import com.fang.common.common.CommonConstants;
import com.fang.common.common.CommonResult;
import com.fang.common.exception.NetworkDiskException;
import com.fang.common.util.CommonResultUtil;
import com.fang.gateway.entity.po.TbNetDisUser;
import com.fang.gateway.security.service.AuthorityService;
import com.fang.gateway.security.utils.HandlerUtils;
import com.fang.gateway.security.utils.JWTUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @Description 登录成功处理器
 * @Author Bernie
 * @Date 2024/4/23 10:45
 **/
@Component
public class FluxAuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler {

    @Resource
    private AuthorityService authorityService;

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        String username = (String) authentication.getPrincipal();
//        String password = (String) authentication.getCredentials();
//        List<GrantedAuthority> grantedAuthorities = (List<GrantedAuthority>) authentication.getAuthorities();
        TbNetDisUser ndUser = authorityService.findUserByUsername(username);
        authorityService.addLoginRecord(ndUser.getUserId(), ndUser.getUsername(), CommonConstants.LoginStatus.SUCCESS, null);

        String token = null;
        try {
            token = JWTUtil.signToToken(ndUser.getUsername(), ndUser.getUserId());
        } catch (NetworkDiskException e) {
            CommonResult result = CommonResultUtil.failed(e);
            return HandlerUtils.writeWith(webFilterExchange.getExchange(), result);
        }
        //返回json数据
        CommonResult result = CommonResultUtil.success(token);
        return HandlerUtils.writeWith(webFilterExchange.getExchange(), result);
    }

}
